package com.example.viewdemo;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.RelativeLayout;

/**
 * Created by Administrator on 2016/9/28 0028.
 */

public class DragView extends View {
    private static final String TAG = "DragView";
    private int mwidth,mheight;
    public DragView(Context context) {
        super(context);
    }

    public DragView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public DragView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);
//        Log.e(TAG,"执行了");
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        int x= (int) event.getX();
        int y= (int) event.getY();
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                break;
            case MotionEvent.ACTION_UP:

                break;
            case MotionEvent.ACTION_MOVE:
                //方法一、下面相当于调用onlayout方法。
                //layout(getLeft()+offsetX,getTop()+offsetY,getRight()+offsetX,getBottom()+offsetY);
                //方法二、下面方法等效于上面
//                offsetLeftAndRight(x-mwidth/2);
//                offsetTopAndBottom(y-mheight/2);
                //方法三、
                RelativeLayout.LayoutParams layoutparam= (RelativeLayout.LayoutParams) getLayoutParams();
                layoutparam.leftMargin=getLeft()+x-mwidth/2;//之所以用控件宽度/2为了使鼠标在控件中央。
                layoutparam.topMargin=getTop()+y-mheight/2;
                setLayoutParams(layoutparam);
                break;
        }
        return true;
    }

    /**
     * 设置宽高
     * @param width
     * @param heigh
     */
    public void setWidthAndHei(int width, int heigh) {
        this.mwidth=width;
        this.mheight=heigh;
        Log.e(TAG,"宽度"+mwidth);
    }
}
